package toy.keli.picmap;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import toy.keli.picmap.adapter.ImageListAdapter;
import toy.keli.picmap.model.Weixin;
import toy.keli.picmap.model.def;
import toy.keli.picmap.model.map;
import toy.keli.picmap.model.system;
import toy.keli.picmap.model.types.PhotoItem;
import toy.keli.picmap.service.KpmReceiver;
import toy.keli.picmap.tools.Control;


/**
 * 图片列表展示
 */
public class PicActivity extends BaseActivity {
    public static final String TAG = "PicActivity";
    public static final int MAX_IMAGES = 9;// 最大图片数量
    public static PicActivity instance;
    public  List<PhotoItem> mDatas = new ArrayList<>();
    public  ImageListAdapter mAdapter;
    public TextView mSelectFinished;
    private ImageView mGoBack;
    private KpmReceiver myReceiver;
    public float winWidth;
    public float winHeight;
    String id;
    String type;        //open,share,
    PicOne onePic;
    /**
     *
      * @param savedInstanceState
     * @paramaa id 怎么传进来？？
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance=this;
        //获取传递的值
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        type = intent.getStringExtra("type");
        Point point = system.getScreenSize(this);
        winWidth=point.x;   winHeight=point.y;
        def all=map.openId(id);

        for(def v: all){
            PhotoItem pic=new PhotoItem();
            pic.setId(v.get("id").toInt());
            pic.setPath(v.get("file").toString());
            pic.setName(v.get("name").toString());
            pic.setCreateTime(Long.valueOf(v.get("intime").toString()));
            v.toObject(pic);
            mDatas.add(pic);
        }
        onePic=new PicOne(this);

        //一张图片的话直接现实图片
        if(mDatas.size()==1) {
            onePic.show(0);
            return;
        }
        setTheme(Control.fullScreenEnable ? R.style.FullActivity:  R.style.AppTheme_PopupOverlay);
        setContentView(R.layout.activity_pics);
        initView();
        initEvent();
//        testCp();
//        testBr();
        //API24以上系统分享支持file:///开头  https://blog.csdn.net/qq_41466437/article/details/102827692
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        if(type.equals(""))   type="open";
        if(!type.equals("open")){
            enableSelect();
        }
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        winWidth=winWidth+winHeight;
        winHeight=winWidth-winHeight;
        winWidth=winWidth-winHeight;

        if(onePic.isShowing()) onePic.show();
        mAdapter.setRowSize(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE? 8:4);
    }

    private void testBr() {
        //发送广播
        sendBroadcast(new Intent("com.example.broadcasttest.MY_BROADCAST"));
        //动态注册网络状态改变事件
        myReceiver = new KpmReceiver();
        IntentFilter itFilter = new IntentFilter();
        itFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(myReceiver, itFilter);
    }
    private void testCr() {
        Uri uri_job = Uri.parse("content://toy.keli.picmap/test");
        ContentResolver resolver2 =  getContentResolver();
        Cursor cursor2 = resolver2.query(uri_job, new String[]{"id","file"}, "id=1", null, null);
        while (cursor2.moveToNext()){
            System.out.println("query job:" + cursor2.getInt(0) +" "+ cursor2.getString(1));
            // 将表中数据全部输出
        }
        cursor2.close();
    }

    private void initView() {
        mGoBack = findViewById(R.id.go_back);
        mSelectFinished = findViewById(R.id.select_count);
        TextView cb = (TextView) findViewById(R.id.count);
        cb.setText("图片("+mDatas.size()+"张)");

        mAdapter = new ImageListAdapter();
        //mAdapter.setRowSize(getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE? 8:4);
        RecyclerView recyclerView = findViewById(R.id.recycler_view_picker);
//        recyclerView.seton
        //显示适配器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false);
        // 设置布局管理器
        recyclerView.setLayoutManager(gridLayoutManager);
        // 设置适配器
        recyclerView.setAdapter(mAdapter);
        mAdapter.setData(mDatas);
        //mAdapter.notifyDataSetChanged();
//        onShopPic(0);
    }
    private void initEvent() {
        mAdapter.itemEvents=new ImageListAdapter.ItemEvents() {
            @Override
            public void onClick(int i) {
                onePic.show(i);
            }

            @Override
            public void onSelect(int i,int count) {
                mSelectFinished.setVisibility(View.VISIBLE);
                mSelectFinished.setText("分享("+count+")");
            }
            @Override
            public void onChange(boolean f) {
                int index = onePic.index + (f ? 1 : -1);
                if(index < 0 || index >= mDatas.size() ) {
                    if(index<0) Toast.makeText(PicActivity.this, "已经是第一张了", Toast.LENGTH_SHORT).show();
                    index=0;
                }
                onePic.show(index);
            }
        };
        mGoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mSelectFinished.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sharePic(true);
            }
        });

        mSelectFinished.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                sharePic(false);
                return true;
            }
        });
    }

    @Override
    public void onBackPressed() {
        if(mSelectFinished.getVisibility()==View.VISIBLE && type.equals("open")) {
            disableSelect();
        }else
            super.onBackPressed();
    }
    void enableSelect(){
        mSelectFinished.setVisibility(View.VISIBLE);
        mAdapter.setEnableSelect(true);
    }
    void disableSelect(){
        mSelectFinished.setVisibility(View.GONE);
        mAdapter.setEnableSelect(false);
    }
    public void sharePic(boolean b) {
        switch (type){
            case "share":   //分享pmr包
                Intent intent = new Intent();
                List<PhotoItem> pics = mAdapter.getSelectedImages();
                int[] ids=new int[pics.size()];
                for (int i = 0; i < pics.size(); i++) {
                    ids[i]=pics.get(i).id;
                }
                intent.putExtra("ids", ids);
                this.setResult(Activity.RESULT_OK,intent);
                this.finish();
                //super.onBackPressed();
                break;
            case "open":    //分享图片
            default:
                new Weixin(this).sharePicture(mAdapter.getSelectedImages(),b);
        }
        //关闭选中
        mSelectFinished.setVisibility(View.GONE);
        mAdapter.setEnableSelect(false);
    }
}

